package com.example.revise

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.example.revise.databinding.ActivityMainBinding
import com.google.android.material.navigation.NavigationView
import org.json.JSONArray
import org.json.JSONObject
import java.io.File

class MainActivity : AppCompatActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityMainBinding

    companion object {
        private const val FOLDER_NAME = "revise"
        private const val FILE_NAME = "menu.json"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 检查文件夹是否存在
        val folder = File(getExternalFilesDir(null), FOLDER_NAME)
        if (!folder.exists()) {
            // 创建文件夹
            folder.mkdirs()
        }

        // 创建或覆盖文件
        val file = File(folder, FILE_NAME)
        try {
            // 直接写入 JSON 内容，不管文件是否存在
            val initialMenu = JSONObject().apply {
                put("menu_items", JSONArray().apply {
                    put(JSONObject().apply {
                        put("title", "示例菜单项")
                        put("description", "这是一个示例菜单项")
                    })
                })
            }
            file.writeText(initialMenu.toString(2))
        } catch (e: Exception) {
            e.printStackTrace()
        }

        // 设置工具栏
        setSupportActionBar(binding.appBarMain.toolbar)

        // 设置导航抽屉
        val navView: NavigationView = binding.navView
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        
        appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow
            ), binding.drawerLayout
        )
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }
}